<script setup lang="ts">
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts'
// @ts-expect-error 引入中文包
import zhCN from 'echarts/lib/i18n/langZH.js'
import { GridComponent, LegendComponent, TitleComponent, TooltipComponent, VisualMapComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import ElementResizeDetectorMaker from 'element-resize-detector'

const props = withDefaults(defineProps<{
  option: echarts.EChartsCoreOption
  height?: string
}>(), {
  height: '300px',
})

const erd = ElementResizeDetectorMaker()

echarts.use([
  BarChart,
  PieChart,
  LineChart,
  RadarChart,
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  VisualMapComponent,
  CanvasRenderer,
])
echarts.registerLocale('zh-CN', zhCN)

// chart 必须是 普通对象 不能为 响应式对象
// 防止 echart tooltip 不显示的问题
// const testRef = ref()
// const testShallowRef = shallowRef()
// const testFunc = () => ({ a: 1 })
// const test = testFunc()
// testRef.value = test
// testShallowRef.value = test
// console.log(testRef.value === test) // -> false
// console.log(testShallowRef.value === test) // -> true

let chart: echarts.ECharts | null = null

const container = ref<HTMLElement>()
function init() {
  if (container.value) {
    const ec = chart = echarts.init(container.value, undefined, { locale: 'zh-CN' })
    ec.setOption({
      ...props.option,
      tooltip: {
        ...(props.option.tooltip || {}),
        backgroundColor: 'rgb(4, 56, 141)',
        borderColor: '#507ab0',
        textStyle: {
          color: '#f9f9f9',
        },
      },
    })
  }
}

const styleObj = computed(() => {
  return `
    width: 100%;
    height: ${props.height}
  `
})

watch(() => props.option, () => {
  if (chart) {
    chart.setOption(props.option)
  }
}, { deep: true })

function resizeHandler() {
  chart?.resize({
    animation: {
      duration: 1000,
    },
  })
}
function bindResizeEvent() {
  erd.listenTo(container.value as HTMLElement, resizeHandler)
}
function unbindResizeEvent() {
  erd.removeListener(container.value as HTMLElement, resizeHandler)
}

onBeforeUnmount(() => {
  unbindResizeEvent()
})

onMounted(() => {
  init()
  nextTick(() => {
    bindResizeEvent()
  })
})
</script>

<template>
  <div ref="container" :style="styleObj" />
</template>
